
//
//  AppDelegate.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/20.
//  Copyright © 2016年 czd. All rights reserved.
//
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#import "IQKeyboardManager.h"

#define IS_PAD (UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPad)
#import "DES3Util.h"
#import "GDataDefines.h"
#import "UMessage.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
#import <UserNotifications/UserNotifications.h>
#endif
#import "AppDelegate.h"
#import "MainViewController.h"
#import "OALoginViewController.h"
#import "AppDelegate+Extendion.h"
#import "MainTabBarController.h"
#import "MenuViewController.h"
#import "LockController.h"
#import "ipadloginViewController.h"
#import "BaseModel.h"
@interface AppDelegate ()<SangforSDKDelegate,UNUserNotificationCenterDelegate>



@end
@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
short port = 443;                        //vpn设备端口号，一般为443
NSString *vpnIp =    @"122.224.123.170";  //vpn设备IP地址
 // 到期时间:2017-12-20
    NSString *copyRight = @"SxD/phFsuhBWZSmMVtSjKZmm/c/3zSMrkV2Bbj5tznSkEVZmTwJv0wwMmH/+p6wLiUHbjadYueX9v51H9GgnjUhmNW1xPkB++KQqSv/VKLDsR8V6RvNmv0xyTLOrQoGzAT81iKFYb1SZ/Zera1cjGwQSq79AcI/N/6DgBIfpnlwiEiP2am/4w4+38lfUELaNFry8HbpbpTqV4sqXN1WpeJ7CHHwcDBnMVj8djMthFaapMFm/i6swvGEQ2JoygFU3CQHU1ScyOebPLnpsDlQDzFl6PdtDy57kFV+RWJq+MePx6aD2yiupr6ji7hzsE6/QbaqCDCtTDTe1U1UGNQSK3L4KSzPvnels6ZNbT7bd4+uVWEbHWAH22+t7LdPt+jENkzZtnNzztENURpEKuLOcS89+ejXAkO7Uf1YSlJfm5PCSgCNRP4FpYjl8hG/IVrYXg+4ZXoWKUbJ3lGm6U3gyeOW8fXpxdRHfEuWC1PB9ruQ=";
    // 检测授权码的有效期
//    NSUInteger expireDateDays = [iAppOffice checkCopyRight:copyRight];
//    if (expireDateDays > 0) {
//        // 注册APP
//        [iAppOffice registerApp:copyRight wpsKey:nil];
//        // 设置端口
//        [iAppOffice setPort:3122];
//        // 设置调试模式
//#ifdef DEBUG
//        [[iAppOffice sharedInstance] setDebugMode:YES];
//#else
//        [[iAppOffice sharedInstance] setDebugMode:NO];
//#endif
//        // 打印授权结果和授权信息
//        NSLog(@"AppDelegate: <-[application:didFinishLaunchingWithOptions:] 授权结果：[%d]", [iAppOffice sharedInstance].isAuthorized);
//        for (NSString *key in [iAppOffice sharedInstance].authorizedInfo.allKeys) {
//
//            NSLog(@"   %@ = %@", key, [[iAppOffice sharedInstance].authorizedInfo objectForKey:key]);
//        }
//        NSLog(@"}>");
//        //注册通知
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleWPSDocumentNotification:) name:@"WPSDocumentNotification" object:nil];
//    }

//iq键盘
 [IQKeyboardManager sharedManager].enable = YES;

[IQKeyboardManager sharedManager].enableAutoToolbar = NO;
 [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
 //友盟推送
//    [UMessage startWithAppkey:@"59db1c4aaed1796af4000130" launchOptions:launchOptions];
//iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate=self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10   completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            //这里可以添加一些自己的逻辑
        } else {
            //点击不允许
            //这里可以添加一些自己的逻辑
        }
    }];
    //打开日志，方便调试
    [UMessage setLogEnabled:YES];
    //高级功能加入
    if ( [[[UIDevice currentDevice] systemVersion] floatValue] >= 10) {
        /*ios10以上*/
        UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"打开" options:UNNotificationActionOptionForeground];

        UNTextInputNotificationAction *action2 = [UNTextInputNotificationAction actionWithIdentifier:@"action2" title:@"清除" options:UNNotificationActionOptionDestructive textInputButtonTitle:@"textInputButtonTitle" textInputPlaceholder:@"textInputPlaceholder"];

        UNNotificationCategory *category1 = [UNNotificationCategory categoryWithIdentifier:@"Category1" actions:@[action2,action1]  intentIdentifiers:@[@"action1",@"action2"] options:UNNotificationCategoryOptionCustomDismissAction];

        UNNotificationAction *action3 = [UNNotificationAction actionWithIdentifier:@"action3" title:@"查看" options:UNNotificationActionOptionForeground];

        UNNotificationAction *action4 = [UNNotificationAction actionWithIdentifier:@"action4" title:@"关闭" options:UNNotificationActionOptionAuthenticationRequired];

        UNNotificationCategory *category2 = [UNNotificationCategory categoryWithIdentifier:@"Category2" actions:@[action3,action4]  intentIdentifiers:@[@"action3",@"action4"] options:UNNotificationCategoryOptionCustomDismissAction];
        //注册
        [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category1,category2, nil]];

        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
            NSLog(@"completionHandler");
        }];

    }else{
        /*ios10以下*/
        UIMutableUserNotificationAction * action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1";
        action1.title=@"查看";
        action1.activationMode = UIUserNotificationActivationModeForeground;
        action1.destructive = YES;

        UIMutableUserNotificationAction * action2 = [[UIMutableUserNotificationAction alloc] init];
        action2.identifier = @"action2";
        action2.title=@"关闭";
        action2.activationMode = UIUserNotificationActivationModeBackground;
        action1.activationMode = UIUserNotificationActivationModeForeground;
        action1.destructive = YES;

        UIMutableUserNotificationCategory * category1 = [[UIMutableUserNotificationCategory alloc] init];
        category1.identifier = @"Category1";
        [category1 setActions:@[action2,action1] forContext:(UIUserNotificationActionContextDefault)];
        //注册
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:[NSSet setWithObjects: category1, nil]];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }


 //推送注册
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;

 self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds] ;
 
 
 if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"shoushi"] isEqualToString:@"Y"]) {
  LockController *lockController = [[LockController alloc]init];
         self.window.rootViewController = lockController;
}else{
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"autoLogin"] isEqualToString:@"Y"]) {
////    _helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
////    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
//[NSThread sleepForTimeInterval:2.0];
////
////      MainViewController * mainVC = [storyBoard instantiateViewControllerWithIdentifier:@"MainVC"];
////        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:mainVC];
////         self.window.rootViewController = navVC;
//
// MenuViewController *tar = [[MenuViewController alloc]init];
//                   self.window.rootViewController = tar;
//                     }else{

   if (IS_IPHONE) {
        OALoginViewController * loginVC = [storyBoard instantiateViewControllerWithIdentifier:@"LoginVC"];

        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                        loginVC.navigationController.navigationBar.hidden = YES;

                 self.window.rootViewController = navVC;
}else{
    ipadloginViewController * loginVC = [storyBoard instantiateViewControllerWithIdentifier:@"ipadLoginVC"];

        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                        loginVC.navigationController.navigationBar.hidden = YES;

                 self.window.rootViewController = navVC;

}

//    }
  }

    [self.window makeKeyAndVisible];
    [self dismissKeyBoard];
    return YES;
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [UMessage registerDeviceToken:deviceToken];
  
    NSString *dt = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                     stringByReplacingOccurrencesOfString: @">" withString: @""]
                    stringByReplacingOccurrencesOfString: @" " withString: @""];
    // 获取用户偏好设置对象
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    // 保存用户偏好设置
        [defaults setObject:dt forKey:@"deviceToken"];

//
    [defaults synchronize];
}





- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
//    int ssl_vpn_quit();

 [[iAppOffice sharedInstance] setApplicationDidEnterBackground:application];
    [_helper logoutVpn];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
NSString *vpnIp =    @"220.191.244.22";  //vpn设备IP地址
short port = 443;                        //vpn设备端口号，一般为443

if([_helper queryVpnStatus] ==VPN_STATUS_OK){
//  [self setin];
 NSLog(@"111");

 }else{
//  self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
//
//
//    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
                 }
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
#pragma Mark VPNDelegate
- (void) onCallBack:(const VPN_RESULT_NO)vpnErrno authType:(const int)authType
{NSString *userName = @"oa2";             //用户名认证的用户名
NSString *password = @"a1a1a1";                //用户名认证的密码
    switch (vpnErrno)
    {
        case RESULT_VPN_INIT_FAIL:
            NSLog(@"Vpn Init failed!");
            break;
        
        case RESULT_VPN_AUTH_FAIL:
            [self.helper clearAuthParam:@SET_RND_CODE_STR];
            NSLog(@"Vpn auth failed!");
            break;
        
        case RESULT_VPN_INIT_SUCCESS:
            NSLog(@"Vpn init success!");
            //设置认证参数 用户名和密码以数值map的形式传入
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
            //开始用户名密码认证
            [self.helper loginVpn:SSL_AUTH_TYPE_PASSWORD];
            break;
        case RESULT_VPN_AUTH_SUCCESS:
            [self startOtherAuth:authType];
            break;
        case RESULT_VPN_AUTH_LOGOUT:
            NSLog(@"Vpn logout success!");
            break;
        case RESULT_VPN_OTHER:
            if (VPN_OTHER_RELOGIN_FAIL == (VPN_RESULT_OTHER_NO)authType) {
                NSLog(@"Vpn relogin failed, maybe network error");
            }
            break;
        
        case RESULT_VPN_NONE:
            break;
        
        default:
            break;
    }
}

- (void) startOtherAuth:(const int)authType
{
NSString *userName = @"oa2";             //用户名认证的用户名
NSString *password = @"a1a1a1";                //用户名认证的密码
NSString *certName = @"";     //导入证书名字，如果服务端没有设置证书认证可以不设置
NSString *certPwd =  @"";          //证书密码，如果服务端没有设置证书
    NSArray *paths = nil;
    switch (authType)
    {
        case SSL_AUTH_TYPE_CERTIFICATE:
            paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                        NSUserDomainMask, YES);
        
            if (nil != paths && [paths count] > 0)
            {
                NSString *dirPaths = [paths objectAtIndex:0];
                NSString *authPaths = [dirPaths stringByAppendingPathComponent:certName];
                NSLog(@"PATH = %@",authPaths);
                [self.helper setAuthParam:@CERT_P12_FILE_NAME param:authPaths];
                [self.helper setAuthParam:@CERT_PASSWORD param:certPwd];
            }
            NSLog(@"Start Cert Auth!!!");
            break;
        
        case SSL_AUTH_TYPE_PASSWORD:
            NSLog(@"Start Password Name Auth!!!");
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
        
            break;
        case SSL_AUTH_TYPE_NONE:
            NSLog(@"Auth success!!!");
//            [self upApp];
        
//            [self setin];
            return;
        default:
            NSLog(@"Other failed!!!");
            return;
    }
    [self.helper loginVpn:authType];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(@"222");
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
//    if (![iAppOffice sharedInstance].isAuthorized) {
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"授权失败！" message:@"请检查授权码是否有效。" preferredStyle:UIAlertControllerStyleAlert];
//        [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
//        return;
//    }
    // 检测是否安装了WPS，如未安装给出提示。
//    if (![iAppOffice isAppStoreWPSInstalled]) {
//
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"检测到未安装WPS" message:@"请退出应用安装WPS后重试" preferredStyle:UIAlertControllerStyleAlert];
//        [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
//    }
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // 注销通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"WPSDocumentNotification" object:nil];
    [_helper logoutVpn];

}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    // 重新拉起WPS做相应的配置(回调成功，通知WPS。)
    return [iAppOffice handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
}

#pragma mark - Notification
- (void)handleWPSDocumentNotification:(NSNotification *)notification{
    
    NSLog(@"AppDelegate: <-[handleWPSDocumentNotification:] fileName = %@>", notification.object);
    // 获取文档主路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths firstObject];
    // 获取通知中的文档名称
    NSString *fileName = notification.object;
    // 根据文件名称获取文档路径
    NSString *filePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Files/%@", fileName]];
//    // 根据文件路径拿到文档数据
 NSString * file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * filePath1 = [file stringByAppendingPathComponent:notification.object];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath1];
    // 如果文档数据长度为0,则退出方法.
    NSLog(@"AppDelegate: <-[handleWPSDocumentNotification:] fileData.length = %lu>", (unsigned long)fileData.length);
    if (fileData.length == 0) return;
    
    // 文档权限信息
    NSMutableDictionary *filePolicyInfo = [NSMutableDictionary dictionary];
    // 获取权限设置文件的路径
    NSString *rightsFilePath = [documentsPath stringByAppendingPathComponent:@"Settings/iAppOfficeRightsSetting.plist"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:rightsFilePath]) {// 权限设置文件的路径是存在的会进入
        // 将权限设置文件转成字典
        NSDictionary *rightsDict = [NSDictionary dictionaryWithContentsOfFile:rightsFilePath];
        
        // 公共权限
        NSDictionary *publicDict = [rightsDict objectForKey:@"Public"];
        for (NSDictionary *dict in [publicDict objectForKey:@"Rights"]) {
            // 该条配置信息是否有效
            BOOL available = [[dict objectForKey:@"Available"] boolValue];
            if (available) {
                // 如果是有效的，则将该条配置加入到 文档权限信息字典 中
                [filePolicyInfo setObject:[dict objectForKey:@"Value"] forKey:[dict objectForKey:@"Key"]];
            }
        }
        
        // Word权限
        NSDictionary *wordRightsDict = [rightsDict objectForKey:@"Word"];
        for (NSDictionary *dict in [wordRightsDict objectForKey:@"Rights"]) {
            
            BOOL available = [[dict objectForKey:@"Available"] boolValue];
            if (available) {
                
                [filePolicyInfo setObject:[dict objectForKey:@"Value"] forKey:[dict objectForKey:@"Key"]];
            }
        }
        
        // Excel权限
        NSDictionary *excelRightsDict = [rightsDict objectForKey:@"Excel"];
        for (NSDictionary *dict in [excelRightsDict objectForKey:@"Rights"]) {
            
            BOOL available = [[dict objectForKey:@"Available"] boolValue];
            if (available) {
                
                [filePolicyInfo setObject:[dict objectForKey:@"Value"] forKey:[dict objectForKey:@"Key"]];
            }
        }
        
        // PPT权限
        NSDictionary *pptRightsDict = [rightsDict objectForKey:@"PPT"];
        for (NSDictionary *dict in [pptRightsDict objectForKey:@"Rights"]) {
            
            BOOL available = [[dict objectForKey:@"Available"] boolValue];
            if (available) {
                
                [filePolicyInfo setObject:[dict objectForKey:@"Value"] forKey:[dict objectForKey:@"Key"]];
            }
        }
        
        // PDF权限
        NSDictionary *pdftRightsDict = [rightsDict objectForKey:@"PDF"];
        for (NSDictionary *dict in [pdftRightsDict objectForKey:@"Rights"]) {
            
            BOOL available = [[dict objectForKey:@"Available"] boolValue];
            if (available) {
                
                [filePolicyInfo setObject:[dict objectForKey:@"Value"] forKey:[dict objectForKey:@"Key"]];
            }
        }
    }
    // 打印文档权限信息
    NSLog(@"AppDelegate: <-[handleWPSDocumentNotification:] filePolicyInfo: %@>", filePolicyInfo);
    // 启动WPS打开文档
    [[iAppOffice sharedInstance] sendFileData:fileData fileName:fileName callback:nil delegate:self policy:filePolicyInfo completion:^(BOOL result, NSError *error) {
        
        NSLog(@"AppDelegate: <-[handleWPSDocumentNotification:] sendFileData: result = %d, error = %@>", result, error.description);
        
        if (!result && error != nil) {
            if (error.code == -6) {// 服务未完成，WPS被占用
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"打开失败"
                                                                message:@"WPS被占用，请重新启动WPS。"
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
        
    }];
}

#pragma mark - iAppOfficeApi Delegate
// 在WPS中点击保存数据时调用
//- (void)iAppOfficeDidReceivedData:(NSDictionary *)dict{
- (void)officeDidReceivedData:(NSDictionary *)dict {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refrshdata" object:nil];
    // 打印回调信息dict
    NSLog(@"AppDelegate: <-[officeDidReceivedData:] receivedInfo: {");
    for (NSString *key in dict.allKeys) {
        
        id value = [dict objectForKey:key];
        if ([value isKindOfClass:[NSData class]]) {
            
            NSData *data = (NSData *)value;
            
            NSLog(@"    %@: length = %ld", key, (unsigned long)data.length);
        }
        else {
            
            NSLog(@"    %@: %@", key, [dict objectForKey:key]);
        }
    }
    NSLog(@"}>");
    // 获取文档数据、文档类型、文档名称
    NSData *fileData = [dict objectForKey:@"Body"];
    NSString *fileType = [dict objectForKey:@"FileType"];
    NSString *fileName = [dict objectForKey:@"FileName"];
    // 根据文档名称、文档类型获取文档的存储路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", fileName, fileType]];
    // 保存数据
    BOOL saveFile = NO;
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    //文档路径不存在，新建并写入数据
        saveFile = [[NSFileManager defaultManager] createFileAtPath:filePath contents:fileData attributes:nil];
    }
    else{//文档路径存在，则用新数据替换老数据
        
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        saveFile = [fileData writeToFile:filePath atomically:YES];
    }
          [MBProgressHUD showHUDAddedTo:self.window animated:YES];

            NSData *Data = [NSData dataWithContentsOfFile:filePath];
            NSString *result = [DES3Util encrypt:Data] ;
  NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * fileId = [[NSUserDefaults standardUserDefaults]objectForKey:@"fileId"];

NSArray * array = @[@{@"userId":userId},@{@"unid":fileId},@{@"fjcont":result}];

            [HttpTools postWithURL:@"exchstream" arrays:array method:@"saveWord" success:^(id JSON) {
                    [MBProgressHUD hideAllHUDsForView:self.window animated:YES];

 GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: [JSON dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        GDataXMLElement *rootElement = [doc rootElement];
        NSArray *arrData= [rootElement elementsForName:@"info"];
        NSString * message= nil;
        for (GDataXMLElement * subXMLElement in arrData) {
            GDataXMLElement * element = [[subXMLElement elementsForName:@"msg"] objectAtIndex:0];
            message  = [element stringValue];
        }
        NSLog(@"%@",message);
if ([message isEqualToString:@"20"]) {
            [self.window makeToast:@"保存成功!"];
}else{

[self.window makeToast:@"保存失败!请重试"];
}
    } failure:^(NSError *error) {
    [self.window makeToast:@"保存失败!请重试"];

        [MBProgressHUD hideAllHUDsForView:self.window animated:YES];
    }];
    
    
    
}
// WPS完成编辑，退回到当前App时调用
//- (void)iAppOfficeDidFinished {
- (void)officeDidFinished {
    
    NSLog(@"AppDelegate: <-[officeDidFinished]>");
}
// WPS结束编辑，并退回到后台时调用
//- (void)iAppOfficeDidAbort{
- (void)officeDidAbort {
    
    NSLog(@"AppDelegate: <-[officeDidAbort]>");
    
}
// 和WPS通信传输过程中出现问题调用
//- (void)iAppOfficeDidCloseWithError:(NSError *)error{
- (void)officeDidCloseWithError:(NSError *)error {
    
    NSLog(@"AppDelegate: <-[officeDidCloseWithError:]>");
}

@end

